<template>
  <div>
    <basic-container>
      <el-date-picker
        v-model="datePickerValue"
        type="date"
        @change="datePickerChange"
        value-format="YYYYMMDD"
        placeholder="选择日期"
        :disabled-date="disabledDate"
        style="float: right;">
      </el-date-picker>
      <el-divider style="margin-top: 50px" />
      <el-row justify="center" align="middle"><h3>基础统计</h3></el-row>
      <avue-data-display :option="basicStatisticsOption"></avue-data-display>
    </basic-container>

    <basic-container style="margin-top: -10px">
      <el-row justify="center" align="middle"><h3>Whatsapp统计</h3></el-row>
      <avue-data-display :option="whatsappStatisticsOption"></avue-data-display>
      <div v-show="reasonData" id="reasonChart" style="height: 400px" />
      <el-empty v-show="!reasonData" description="暂无数据" />
    </basic-container>

    <div>
      <el-row>
        <el-col :span="12">
          <basic-container>
            <el-row justify="center" align="middle"><h5>平台统计</h5></el-row>
            <el-collapse accordion v-if="detailData">
              <el-collapse-item v-for="(service, serviceKey) in detailData" :key="serviceKey" :name="serviceKey">
                <template #title>
                  <i class="iconfont bizicon-pingtai el-icon--left" />接码平台
                  <el-divider direction="vertical" border-style="dashed" />
                  <el-tag effect="plain" size="small">{{ serviceKey }}</el-tag>
                </template>
                <el-collapse accordion>
                  <el-collapse-item v-for="(country, countryKey) in service" :key="countryKey" :name="countryKey" style="margin-left: 20px">
                    <template #title>
                      <i class="iconfont bizicon-guojia el-icon--left" />国家
                      <el-divider direction="vertical" border-style="dashed" />
                      <el-tag effect="plain" size="small">{{ countryKey }}</el-tag>
                      <el-divider direction="vertical" border-style="dashed" />
                      <el-text size="small">数量: {{ calculateCount(country) }} ,发送率: {{ calculateSendRate(country) }}% ,回码率: {{ calculateResponseRate(country) }}%</el-text>
                    </template>
                    <el-container>
                      <el-aside width="50%">
                        <el-row justify="center" align="middle"><h5>状态统计</h5></el-row>
                        <el-divider style="margin: 0" />
                        <el-row v-for="(status, statusKey) in country" :key="statusKey" justify="center" align="middle">
                          <el-text size="small">{{ statusKey + ': ' + status }}</el-text>
                        </el-row>
                      </el-aside>
                      <el-divider direction="vertical" border-style="dashed" />
                      <el-main>
                        <el-row justify="center" align="middle"><h5>原因统计</h5></el-row>
                        <el-divider style="margin: 0" />
                        <el-row v-for="(count, reasonKey) in reasonDetailData[serviceKey][countryKey]" :key="reasonKey" justify="center" align="middle">
                          <el-text size="small">{{ reasonKey + ': ' + count }}</el-text>
                        </el-row>
                      </el-main>
                    </el-container>
                  </el-collapse-item>
                </el-collapse>
              </el-collapse-item>
            </el-collapse>
            <el-empty v-else description="暂无数据" />
          </basic-container>
        </el-col>
        <el-col :span="12">
          <basic-container>
            <el-row justify="center" align="middle"><h5>注册排行榜</h5></el-row>
            <el-divider v-if="registerData" style="margin: 0" />
            <div v-show="registerData" id="registerChart" style="height: 400px" />
            <el-empty v-show="!registerData" description="暂无数据" />
          </basic-container>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { statistics } from '@/api/whatsapp/service-phone';
import { mapGetters } from 'vuex';
import * as echarts from 'echarts/core';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { validatenull } from '@/utils/validate';

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
]);
export default {
  data() {
    return {
      disabledDate(time) {
        let dateTime = new Date();
        dateTime = dateTime.setDate(dateTime.getDate() - 1);
        return time.getTime() > new Date(dateTime);
      },
      type: 1,
      datePickerValue: null,
      reasonChart: undefined,
      registerChart: undefined,
      basicStatisticsOption: {
        span: 12,
        data: [
          {
            title: '号码总数',
            count: 0,
            decimals: 0
          },
          {
            title: '消费流量(MB)',
            count: 0,
            decimals: 2
          }
        ]
      },
      whatsappStatisticsOption: {
        span: 4,
        data: [
          { color: 'grey', title: '待发送', count: 0, decimals: 0 },
          { title: '发送中', count: 0, decimals: 0 },
          { color: '#e6a23c', title: '网络异常', count: 0, decimals: 0 },
          { title: '已发送', count: 0, decimals: 0 },
          { color: '#F71735', title: '发送失败', count: 0, decimals: 0 },
          { color: '#28cc9e', title: '注册成功', count: 0, decimals: 0 },
          { color: '#F71735', title: '注册失败', count: 0, decimals: 0 },
          { color: '#e6a23c', title: '等待超时', count: 0, decimals: 0 },
          { color: '#F71735', title: '发送异常', count: 0, decimals: 0 },
          { color: '#F71735', title: '注册异常', count: 0, decimals: 0 }
        ]
      },
      detailData: [],
      reasonData: [],
      reasonDetailData: [],
      registerData: [],
      timer: null
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  mounted() {
    this.onLoadStatistics();
    this.timer = setInterval(() => {
      this.onLoadStatistics();
    }, 5000);
  },
  unmounted() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    calculateCount(country) {
      return Object.values(country).reduce((sum, value) => sum + value, 0);
    },
    calculateSendRate(country) {
      const total = this.calculateCount(country);
      const sent = (country['已发送'] || 0) + (country['注册成功'] || 0) + (country['注册失败'] || 0) + (country['等待超时'] || 0) + (country['注册异常'] || 0);
      return total > 0 ? (sent / total * 100).toFixed(2) : 0;
    },
    calculateResponseRate(country) {
      const sent = (country['已发送'] || 0) + (country['注册成功'] || 0) + (country['注册失败'] || 0) + (country['等待超时'] || 0) + (country['注册异常'] || 0);
      const timeout = (country['已发送'] || 0) + (country['等待超时'] || 0);
      return sent > 0 ? ((sent - timeout) / sent * 100).toFixed(2) : 0;
    },
    onLoadStatistics() {
      statistics({ date: this.datePickerValue }).then(res => {
        let data = res.data.data;

        this.basicStatisticsOption.data.forEach(item => {
          if (item.title === '号码总数') {
            item.count = data.total ? data.total : 0;
          }
          if (item.title === '消费流量(MB)') {
            item.count = data.traffic ? data.traffic / 1000 / 1000 : 0;
          }
        });

        let status = validatenull(data.status) ? [] : data.status;
        this.whatsappStatisticsOption.data.forEach(item => {
          if (status[item.title]) {
            item.count = status[item.title];
          } else {
            item.count = 0;
          }
        });

        this.reasonData = validatenull(data.reason) ? null : data.reason;
        if (this.reasonData) {
          this.onLoadReasonChart(this.reasonData);
        }

        this.detailData = validatenull(data.detail) ? null : data.detail;

        this.registerData = validatenull(data.register) ? null : data.register;
        if (this.registerData) {
          this.onLoadRegisterChart(this.registerData);
        }

        this.reasonDetailData = validatenull(data.reasonDetail) ? null : data.reasonDetail;
      });
    },
    onLoadRegisterChart(data) {
      data = Object.entries(data).map(([name, value]) => ({ name, value }));
      if (this.registerChart) {
        let option = {
          series: [
            { data: data }
          ]
        };
        this.registerChart.setOption(option);
      } else {
        this.$nextTick(() => {
          const chartDom = document.getElementById('registerChart');
          this.registerChart = echarts.init(chartDom);
          let option = {
            title: {
              show: false
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              top: '20px'
            },
            series: [
              {
                name: '数量',
                type: 'pie',
                radius: '50%',
                data: data,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };
          option && this.registerChart.setOption(option);
        });
      }
    },
    onLoadReasonChart(data) {
      data = Object.entries(data).map(([name, value]) => ({ name, value }));
      if (this.reasonChart) {
        let option = {
          series: [
            { data: data }
          ]
        };
        this.reasonChart.setOption(option);
      } else {
        this.$nextTick(() => {
          const chartDom = document.getElementById('reasonChart');
          this.reasonChart = echarts.init(chartDom);
          let option = {
            title: {
              show: false
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: '100px',
              top: '20px'
            },
            series: [
              {
                name: '数量',
                type: 'pie',
                radius: '50%',
                data: data,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };
          option && this.reasonChart.setOption(option);
        });
      }
    },
    datePickerChange() {
      if (this.datePickerValue) {
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
      } else {
        if (!this.timer) {
          this.timer = setInterval(() => {
            this.onLoadStatistics();
          }, 5000);
        }
      }
      this.onLoadStatistics();
    }
  }
};
</script>

<style>

</style>

